#define _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    vector<vector<int>> threeSum(vector<int>& nums) {
        sort(nums.begin(), nums.end());

        vector<vector<int>> ret;
        for (int i = 0; i < nums.size(); ) {
            int left = i + 1;
            int right = nums.size() - 1;
            int rei = -nums[i];
            if (nums[i] > 0) break;

            while (left < right) {
                vector<int> tmp;
                if (nums[left] + nums[right] > rei)
                    right--;
                else if (nums[left] + nums[right] < rei)
                    left++;
                else {
                    tmp.push_back(nums[left++]);
                    tmp.push_back(nums[right--]);
                    tmp.push_back(nums[i]);
                    ret.push_back(tmp);
                    while (left < right && nums[right] == nums[right + 1])
                        right--;

                    while (left < right && nums[left] == nums[left - 1])
                        left++;
                }
            }
            i++;
            while (i < nums.size() && nums[i] == nums[i - 1])
                i++;
        }
        return ret;
    }
};